package com.lvwenguo.controller;

import com.lvwenguo.model.LoginUser;
import com.lvwenguo.service.ServiceInter;
import com.lvwenguo.service.serviceImple.ServiceImple;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


@WebServlet(name = "loginServlet",urlPatterns = "/login")
public class loginServlet extends HttpServlet {

    ServiceInter serviceImpol =new ServiceImple();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String name=  req.getParameter("name");
        String pass=req.getParameter("pass");
        //用户未输入返回错误信息提示用户
        if(name.isEmpty() && pass.isEmpty()){
            System.out.println("名称：null--密码：null");
        }
        //用户输入不为空，判断数据是否存在数据库
        else{
            LoginUser loginUser=new LoginUser();
            loginUser.setLogin_account(name);
            loginUser.setPassword(pass);
            List<LoginUser> list= serviceImpol.selectUser(loginUser);
           if(list.size()==0){
               req.setAttribute("error","用户名或密码错误！检查信息继续登录！");
               req.setAttribute("name",name);
               req.setAttribute("pass",pass);
               req.getRequestDispatcher("/login.jsp").forward(req,resp);
           }
           else {
               for(LoginUser loginUser1:list){

               HttpSession session = req.getSession();
               //存入用户名称与sesstion
               session.setAttribute("sessionname",loginUser1.getLogin_account());
               //存入用户身份信息
               session.setAttribute("role",loginUser1.getRole_name());
               //存入用户头像URL
               session.setAttribute("url",loginUser1.getImgurl());
               resp.sendRedirect("http://localhost:8080/supermarket/index.jsp");
             }
           }




        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
